<template>
  <view>
    <u-upload :previewFullImage="true" :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1"
      multiple :maxCount="limitNum" uploadText="请选择文件">
    </u-upload>
  </view>
</template>

<script>
  import upload from '@/utils/upload.js'
  import config from '@/config.js'

  export default {
    name: "uploadFile",
    props: {
      limit: {
        type: Number,
        default: 5
      },
      // 上传携带的参数
      data: {
        type: Object,
        default () {
          return {}
        }
      },
      // 上传地址
      uploadUrl: {
        type: String,
        default: '/common/UploadFile'
      },
      value: {
        type: [String, null]
      }
    },
    computed: {
      limitNum() {
        return this.limit
      }
    },
    data() {
      return {
        uploadList: [],
        imgList: [],
        //[
        //   {
        //     "type": "image",
        //     "url": "http://localhost:8888/20230630/1FD863C610563953.png",
        //     "thumb": "blob:http://localhost:8886/4df43017-0762-498c-8d3b-4c26a289112f",
        //     "size": 13738,
        //     "name": "icon_15.png",
        //     "status": "success",
        //     "message": ""
        //   }
        // ]
        fileList1: []
      };
    },
    watch: {
      // 监听 v-model 的值
      value: {
        immediate: true,
        deep: true,
        handler: function(val) {
          if (val) {
            // 首先将值转为数组
            const list = Array.isArray(val) ? val : this.value.split(',')
            // 然后将数组转为对象数组
            this.fileList1 = list.map((item) => {
              if (typeof item === 'string') {
                item = {
                  name: item,
                  url: item,
                  status: 'success'
                }
              }
              return item
            })
          } else {
            this.fileList1 = []
            return []
          }
        }
      }
    },
    methods: {
      async afterRead(event) {
        // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
        let lists = [].concat(event.file)
        let fileListLen = this[`fileList${event.name}`].length
        lists.map((item) => {
          this[`fileList${event.name}`].push({
            ...item,
            status: 'uploading',
            message: '上传中'
          })
        })
        for (let i = 0; i < lists.length; i++) {
          const result = await this.uploadFilePromise(lists[i].url)
          let item = this[`fileList${event.name}`][fileListLen]
          this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
            status: 'success',
            message: '',
            url: result
          }))

          this.listToString(this[`fileList${event.name}`])
          fileListLen++
        }
      },
      deletePic(event) {
        this[`fileList${event.name}`].splice(event.index, 1)
        this.listToString(this[`fileList${event.name}`])
        this.imgList.splice(event.index, 1)
      },
      uploadFilePromise(url) {
        return new Promise((resolve, reject) => {
          upload({
            formData: this.data,
            filePath: url,
            url: this.uploadUrl
          }).then(res => {
            if (res.code == 200) {
              resolve(res.data.url)
            }
          })
        })
      },
      // 对象转成指定字符串分隔
      listToString(list, separator = ',') {
        let strs = ''
        // separator = separator || ','
        for (const i in list) {
          strs += list[i].url + separator
        }
        var result = strs != '' ? strs.substr(0, strs.length - 1) : ''

        this.$emit(`input`, result)
        return result
      },
    }
  }
</script>

<style>

</style>